<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div class="text item">
      <img class="acatar" src="@/assets/images/avatar.jpg" alt="" ref="photo" />
      <div>
        <input type="file" name="" id="" ref="input" @change="phout" />
        <el-button type="primary" @click="$refs.input.click()" icon="el-icon-plus"
          >选取文件</el-button
        >
        <el-button
          class="upto"
          type="success"
          :disabled="flag"
          icon="el-icon-upload"
          @click="toupphoto"
          >上传到服务器</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
import { updataAvatarAPI } from '@/api/user'
export default {
  name: 'UserAvatar',
  data() {
    return {
      flag: true,
      useravatar: {
        avatar: ''
      }
    }
  },
  methods: {
    phout() {
      if (!this.$refs.input.files[0]) return
      const photoname = this.$refs.input.files[0]
      const fileName = photoname.name.substring(photoname.name.lastIndexOf('.'))
      if (fileName === '.jpg' || fileName === '.png' || fileName === '.webp') {
        const fl = new FileReader()
        fl.readAsDataURL(photoname)
        fl.addEventListener('load', () => {
          this.$refs.photo.src = fl.result
          this.useravatar.avatar = fl.result
          this.flag = false
        })
      } else {
        this.$message.error('文件格式错误')
      }
    },
    async toupphoto() {
      const { data: res } = await updataAvatarAPI(this.useravatar)
      if (res.code === 0) {
        this.$message.success(res.message)
        this.$store.dispatch('user/getUserInfo')
      } else {
        this.$message.warning(res.message)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.acatar {
  width: 350px;
  height: 350px;
  margin-bottom: 15px;
  object-fit: cover;
}
input {
  display: none;
}
.upto {
  margin-left: 10px;
}
</style>
